/*
 * Copyright (c) 2014, TU Darmstadt
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package scoutobahn.highway;
/**
 * See https://code.google.com/p/d2d-routing/source/browse/trunk/d2d-routing/src/de/tu_darmstadt/informatik/algo/server/geo/GeoPos.java?r=148
 * for more informations.
 *
 */
public class GeoPos {
    /**
     * Berechnet aus zwei Geographischen Punkten (WSG84 Koordinaten)
     * die Entfernung zwischen den Punkten.
     * Ungenau, da nur angenÃ¤hert.
     * http://de.wikipedia.org/wiki/Orthodrome
     * @param lat1 Latitude Punkt 1
     * @param lon1 Longitude Punkt 1
     * @param lat2 Latitude Punkt 2
     * @param lon2 Longitude Punkt 2
     * @return Entfernung in Kilometern
     */
    public static double getDistance(final double lat1,
            final double lon1,
            final double lat2,
            final double lon2) {     
        if (Double.isNaN(lat1) || Double.isNaN(lon1) 
                || Double.isNaN(lat2) || Double.isNaN(lon2)) {
            return Double.NaN;
        }
        
        double lat1_rad = Math.toRadians(lat1);
        double lon1_rad = Math.toRadians(lon1);
        double lat2_rad = Math.toRadians(lat2);
        double lon2_rad = Math.toRadians(lon2);
              
        double a = Math.sin(lat1_rad) * Math.sin(lat2_rad);
        double b = Math.cos(lat1_rad) * Math.cos(lat2_rad) * 
            Math.cos(lon2_rad - lon1_rad);
        
        double c = Math.acos(a + b);
        
        // Entfernung in Kilometern
        return c * 6371.0;
    }
    
    /**
     * Berechnet aus zwei Geographischen Punkten (WSG84 Koordinaten) 
     * die Entfernung zwischen den Punkten.
     * Nach der Formel von Vincenty
     * http://www.movable-type.co.uk/scripts/latlong-vincenty.html
     * 
     * @param lat1 Latitude Punkt 1
     * @param lon1 Longitude Punkt 1
     * @param lat2 Latitude Punkt 2
     * @param lon2 Longitude Punkt 2
     * @return Entfernung in Kilometern
     */
    public static double getDistanceVincenty(double lat1, double lon1, 
            double lat2, double lon2){
    
        // WGS-84 ellipsiod
        double a = 6378137.0;
        double b = 6356752.3142;  
        // double f = 1 / 1/298.257223563
        double f = 3.3528106647474807198455286185206e-12;
        
        double L = Math.toRadians(lon2-lon1);
        double U1 = Math.atan((1.0-f) * Math.tan(Math.toRadians(lat1)));
        double U2 = Math.atan((1.0-f) * Math.tan(Math.toRadians(lat2)));
        double sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
        double sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
          
        double lambda = L, lambdaP, iterLimit = 100;
        double sinLambda,sinSigma,cosLambda,cosSigma,sigma,sinAlpha,cosSqAlpha,cos2SigmaM;
        
        do {
            sinLambda = Math.sin(lambda);
            cosLambda = Math.cos(lambda);
            sinSigma = Math.sqrt((cosU2 * sinLambda) * 
                    (cosU2 * sinLambda) + 
                    (cosU1 * sinU2-sinU1 * cosU2 * cosLambda) * 
                    (cosU1 * sinU2-sinU1 * cosU2 * cosLambda));
            
            if (sinSigma == 0.0) 
                return 0.0;  // co-incident points
            
            cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
            sigma = Math.atan2(sinSigma, cosSigma);
            sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
            cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
            cos2SigmaM = cosSigma - 2.0 * sinU1 * sinU2 / cosSqAlpha;
            
            if (Double.isNaN(cos2SigmaM)) 
                cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (Â§6)
            
            double C = f / 16.0 * cosSqAlpha * (4.0 + f * (4.0 - 3.0 * cosSqAlpha));
            lambdaP = lambda;
            lambda = L + (1.0 - C) * f * sinAlpha *
                (sigma + C * sinSigma * (
                        cos2SigmaM + C * cosSigma * 
                        (-1.0 + 2.0 * cos2SigmaM * cos2SigmaM)));
        }while(Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit > 0);

        if (iterLimit==0) 
            return Double.NaN;  // formula failed to converge

        double uSq = cosSqAlpha * (a*a - b*b) / (b*b);
        double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
        double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
        double deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
                B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
        double s = b*A*(sigma-deltaSigma);
          
        //s = s.toFixed(3); // round to 1mm precision
        return s / 1000.0;
    }
}

